<?php
/*
 * @Date: 2021-05-08 14:19:49
 * @Author: yukun
 * @LastEditors: yukun
 * @LastEditTime: 2021-05-08 14:46:39
 * @FilePath: /design-patterns-study/策略模式/Math.php
 * @Description: 本文件主要功能为：
 */

interface Math
{
    public function calculate($op1, $op2);
}


class Add implements Math
{
    public $operationSymbol = '+';

    public function calculate($op1, $op2)
    {
        return $op1 + $op2;
    }
}

class Sub implements Math
{
    public $operationSymbol = '-';
    
    public function calculate($op1, $op2)
    {
        return $op1 - $op2;
    }
}

class Mul implements Math
{
    public $operationSymbol = '*';
    
    public function calculate($op1, $op2)
    {
        return $op1 * $op2;
    }
}
 
class Div implements Math
{
    public $operationSymbol = '/';
    
    public function calculate($op1, $op2)
    {
        if ($op2 == 0) {
            throw new Exception("除数不能为0", 1);
        }

        return $op1 / $op2;
    }
}


class CMath
{
    protected $calc = null;

    public function __construct($operationType)
    {
        $this->calc = new $operationType();
    }

    public function calculate($op1, $op2)
    {
        return $this->calc->calculate($op1, $op2);
    }

    public function getOperationSymbol()
    {
        return $this->calc->operationSymbol;
    }
}

$operationTypeArr = ['Add', 'Sub', 'Mul', 'Div'];
$op1 = rand(1, 10);
$op2 = rand(1, 10);
$operationType = $operationTypeArr[rand(0, 3)];

$cmath  = new CMath($operationType);
$result = $cmath->calculate($op1, $op2);

echo "结果：{$op1} {$cmath->getOperationSymbol()} {$op2} = {$result}" . PHP_EOL;